@file:Suppress("DEPRECATION")

package com.c.ctgproject.ui.login

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.c.ctgproject.R
import com.c.ctgproject.utils.*
import com.google.gson.Gson
import com.jaeger.library.StatusBarUtil
import kotlinx.android.synthetic.main.activity_login.*
import android.util.Base64
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import com.c.ctgproject.base.CTGproject
import com.c.ctgproject.base.MyBaseApplication
import com.c.ctgproject.entity.LoginEntityV2
import com.c.ctgproject.entity.guang.LoginNewEntity
import com.c.ctgproject.http.*
import com.c.ctgproject.mode.MyConstants
import com.c.ctgproject.retrofit.Constants
import com.c.ctgproject.service.ResidentService
import com.c.ctgproject.ui.collect.CollectCarHomeActivity
import com.c.ctgproject.ui.collect.PrivacyAgreementActivity
import com.c.ctgproject.wiget.dialog.LoadingDialog
import com.c.ctgproject.wiget.dialog.UpdateDialog
import okhttp3.ResponseBody
import org.jetbrains.anko.startActivity
import org.json.JSONObject
import java.util.ArrayList

/**
 * 登录 页面
 */
class LoginActivity : AppCompatActivity() {
    private val statusColor: StatusColor = StatusColor()
    private val loginViewModel: LoginViewModel by lazy { ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application))[LoginViewModel::class.java] }
    private val loadingDialog: LoadingDialog by lazy { LoadingDialog(this) }
    private val permissionList = ArrayList<String>()//未申请的权限
    private val mRequestCode = 100//权限申请返回值

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setTranslucent(this)
        setContentView(R.layout.activity_login)
        statusColor.setAndroidNativeLightStatusBar(this, true)
        AndroidBottomSoftBar.assistActivity(findViewById(android.R.id.content), this)
        //开启保活Service
        startService(Intent(this, ResidentService::class.java))
        checkPermission()
        event()
        callbackListener()
        mYS.setOnClickListener {
            startActivity<PrivacyAgreementActivity>()
        }
    }

    private fun callbackListener() {
        username_et.textSet(getPhone())

        if (BoWenUtils.isDEBUG()) {
//            username_et.textSet("13621161596")
//            password_et.textSet("13621161596")
//            username_et.textSet("13300000000")
            username_et.textSet("14400005555")
            password_et.textSet("123456")
        }

        //版本检查回调更新
        loginViewModel.updateEntity.observe(this, Observer { entity ->
            if (entity == null) return@Observer
            if (entity.status == 1) {
                //判定更新
                when (entity.data?.forceUpdate) {
                    null -> {
                        //当前是最新版本 进行token登录
                        tokenLogin()
                    }
                    "1" -> {
                        UpdateDialog(this@LoginActivity, R.style.MillionDialogStyle, entity.data?.versionUrl.handlerNull()).show()
                    }
                    "0" -> {
                        if (!CTGproject.getBaseApplication().isDownloadApk) {
                            //修复更新
                            AlertDialog.Builder(this@LoginActivity)
                                .setCancelable(false)
                                .setTitle("更新")
                                .setMessage(entity.data?.versionDesc)
                                .setPositiveButton("下载安装") { _, _ ->
                                    UpdateDialog(this@LoginActivity, R.style.MillionDialogStyle, entity.data?.versionUrl.handlerNull()).show()
                                }
                                .setNegativeButton("取消") { _, _ ->
                                    //取消非自动更新 进行自动登录
                                    tokenLogin()
                                }.show()
                        }
                    }
                    else -> {
                        //当前是最新版本 进行token登录
                        startActivity<CollectCarHomeActivity>()
                    }
                }
                if (entity.data == null) {
                    if (userToken.isNotEmpty()) {
                        startActivity<CollectCarHomeActivity>()
                        finish()
                    }
                }

            } else {
                CustomToast.showToast(this@LoginActivity, entity.msg.handlerNull())
            }
        })
        //自动登录结果回调
        loginViewModel.autoLoginEntity.observe(this, Observer {
            if (it == null) return@Observer
            loadingDialog.dismiss()
            MyLog.d("自动登录回调$it")
            handlerLogin(it)
        })
        //网络请求错误监听回调
        loginViewModel.errorMsg.observe(this, Observer {
            MyLog.d(it)
            if (it.isEmpty()) return@Observer
            CustomToast.showToast(this, it)
        })
    }

    private fun tokenLogin() {
//        //取消非自动更新 进行自动登录
//        val token = sharedGet(Constants.TOKEN, "") as String
//        if (token.isNotEmpty()) {
//            startActivity<CollectCarHomeActivity>()
////            loginViewModel.tokenLogin(token)
//        }
    }

    private fun event() {
        //判断app更新
        var versionName = this@LoginActivity.packageManager.getPackageInfo(this@LoginActivity.packageName, 0).versionName
        versionName = "v$versionName"
        loginViewModel.checkUpdate(versionName)
        //登录按钮
        loginbtn.setOnClickListener {
            loginClick()
        }
        mLoginTypeTV.setOnClickListener {
            startActivity<ForgetPasswordActivity>()
        }
    }

    //登录按钮
    private fun loginClick() {
        when {
            TextUtils.isEmpty(username_et.text.handlerNull()) -> {
                showToast("用户名不能为空")
                username_et.myShake()
            }
            TextUtils.isEmpty(password_et.text.handlerNull()) -> {
                showToast("密码不能为空")
                password_et.myShake()
            }
            username_et.text.handlerNull().length<11->{
                showToast("请输入完整的手机号码")
                username_et.myShake()
            }
            else -> {
                if (NetworkUtils.isConnected(applicationContext)) {
                    val loginListener = object : ObserverListener {
                        override fun onNext(t: ResponseBody) {
                            val result = t.string().handlerNull()
                            handlerLogin(result)
                        }

                        override fun onError(error: String) {
                            MyLog.d("登录失败$error")
                            MyLog.d(error)
                        }
                    }
                    val map = HashMap<String, Any>()
                    map["telephone"] = username_et.text.handlerNull()
                    map["password"] = Base64.encodeToString(password_et.text.toString().toByteArray(), Base64.DEFAULT)
                    map["key"] = handlerPassword("ctgStw_fox^uoe29237gjsl!erq")
                    map["platform"] = "CTG_DISASSEMBLY_ANDROID"
//                    map["key"] = "Y3RnU3R3X3NuYWtlMjk0SUVMRE1GSiYkOTIyUFdza2Q2Nno="
//                    map["platform"] = "CTG_DISASSEMBLY"
                    map["industry"] = "AGENCY"
                    ApiMethods.apiSubscribe(ApiMethods.urmRetrofit.login(handlerBody(map)), MyObserverHandlerLoading(this, loadingDialog, zeroIsSuccess = true) {
                        MyLog.d("回调:$it")
                        handlerLoginV2(it)

                    })


//                    ApiMethods.login(
//                        MyObserver(this, loginListener), handlerBody("telephone" to username_et.text.handlerNull(), "password" to Base64.encodeToString(password_et.text.toString().toByteArray(), Base64.DEFAULT))
//                    )
                } else {
                    Toast.makeText(applicationContext, "请检查您的网络是否连接", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun handlerLoginV2(str: String) {
        val data = getGson().fromJson(str, LoginNewEntity::class.java).data
        data?.let { d ->
            //保存登录状态和用户token
            sharedSave {
                putString(Constants.TOKEN, d.token)
                putString(Constants.USER_Name, d.realName)
                putInt(Constants.USER_Id, d.userId)


//                putString(Constants.LOGIN_STATU, "0")
                //将用户登录的信息保存到本地
//                putString(MyConstants.USER_INFO, result)
            }
            userToken = d.token.handlerNull()
            MyBaseApplication.userName = data.realName.handlerNull()
            MyBaseApplication.userId = data.userId
            startActivity<CollectCarHomeActivity>()
        }


    }


    private fun handlerLogin(result: String) {
        MyLog.d("登录信息$result")
        val json = JSONObject(result)
        val jsonStatue = json.optInt("status", -1)
        if (jsonStatue == 1) {
            val entity = Gson().fromJson(result, LoginEntityV2::class.java)
            MyLog.d("保存所有菜单信息")
            //保存登录状态和用户token
            sharedSave {
                putString(Constants.TOKEN, entity.data?.token)
                putString(Constants.LOGIN_STATU, "0")
                //将用户登录的信息保存到本地
                putString(MyConstants.USER_INFO, result)
            }
            MyBaseApplication.mMenuList.clear()
            entity?.data?.menus?.forEach {
                it.menuCode?.let { bean ->
                    MyBaseApplication.mMenuList.add(bean)
                }
            }
            entity?.data?.let { parent ->
                parent.telephone.handlerNull().savePhone()
                MyBaseApplication.userName = parent.userName.handlerNull()
                parent.token?.let { token ->
                    userToken = token
                    //设置别名
                    ApiMethods.token = token
                }
                sharedSave {
                    putString(MyConstants.MENU_CODES, getGson().toJson(parent))
                }
            }
            startActivity<CollectCarHomeActivity>()
            finish()
        } else {
            showToast(json.optString("msg", "系统异常,请稍后再试"))
        }
    }


    //权限检查
    private fun checkPermission() {
        //将需要的权限放入数组
        val permission: Array<String> = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
        )
        //清除未申请的权限列表
        permissionList.clear()
        //对权限进行排查将未申请的权限放入List
        for (i in permission.indices) {
            if (ContextCompat.checkSelfPermission(this, permission[i]) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission[i])
            }
        }

        if (permissionList.size > 0) {//有权限为通过需要申请
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(permission, mRequestCode)
            }
        }
    }

    //权限回调
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == mRequestCode) {
            checkPermission()
        }
    }

    override fun onBackPressed() {
        val currentTime = System.currentTimeMillis()
        //两次点击间隔小于2秒可以退出
        if (currentTime - nowTime < 2000) {
            AppManager.instance.exitApp(this)
            finish()
        } else {
            CustomToast.showToast(this, "再次点击退出")
        }
        nowTime = currentTime
    }

    override fun onDestroy() {
        super.onDestroy()
        loadingDialog.dismiss()
    }

    private fun String.savePhone() {
        val sp = MyBaseApplication.getContext().getSharedPreferences("phone", Context.MODE_PRIVATE)
        sp.edit().putString("phone", this).apply()
    }

    private fun getPhone(): String {
        val sp = MyBaseApplication.getContext().getSharedPreferences("phone", Context.MODE_PRIVATE)
        return sp.getString("phone", "").handlerNull()
    }
}